<template>
  <div class="product-detail-container">
    <div class="product-header">
      <div class="back-button" @click="$router.back()">
        <el-icon><ArrowLeft /></el-icon> 返回
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-skeleton style="width: 100%" :rows="10" animated />
    </div>

    <div v-else-if="error" class="error-container">
      <el-empty description="获取商品信息失败" :image-size="200">
        <el-button @click="fetchProductDetail">重新加载</el-button>
      </el-empty>
    </div>

    <div v-else>
      <!-- 商品主要信息区域 -->
      <div class="product-main">
        <!-- 商品图片轮播 -->
        <div class="product-images">
          <el-carousel height="400px" indicator-position="outside" v-if="product.images && product.images.length">
            <el-carousel-item v-for="(image, index) in product.images" :key="index">
              <img :src="image.thumbnail_url" class="carousel-image" />
            </el-carousel-item>
          </el-carousel>
          <div class="no-image" v-else>暂无图片</div>
        </div>

        <!-- 商品基本信息 -->
        <div class="product-info">
          <div class="product-header">  <!-- 新增包裹容器 -->
            <h1 class="product-name">{{ product.name }}</h1>
            <div class="seller-meta" v-if="product.seller">  <!-- 修改判断条件 -->
              <el-avatar 
                :size="32" 
                :src="product.seller.avatar || DEFAULT_AVATAR" 
                class="seller-avatar"
                @error="handleAvatarError"
              />
              <span class="seller-name">卖家：{{ product.seller.username }}</span>
            </div>
          </div>
          <div class="product-price">¥{{ product.price }}</div>
          <div class="product-meta">
            <div class="product-status">
              状态: 
              <span :class="{'status-active': product.status === 1, 'status-inactive': product.status !== 1}">
                {{ product.status === 1 ? '在售' : '已售出' }}
              </span>
            </div>
            
            <div class="product-category" v-if="product.category">
              分类: <span>{{ getCategoryName(product.category) }}</span>
            </div>
          </div>

          <!-- 配送信息 -->
          <div class="info-section">
            <h3 class="section-title">配送信息</h3>
            <div class="delivery-method">
              配送方式: {{ getDeliveryMethodText(product.delivery_method) }}
            </div>
            <div class="delivery-location" v-if="product.delivery_location">
              配送地点: {{ product.delivery_location }}
            </div>
          </div>

          <!-- 操作按钮 -->
          <div class="action-buttons-container">
  <div class="action-buttons">
    <el-button
      type="primary"
      class="contact-btn"
      :disabled="product.status !== 1"
      @click="contactSeller">
      联系卖家
    </el-button>
    <el-button
      :class="{'favorite-btn': true, 'is-favorite': isFavorite}"
      @click="toggleFavorite">
      <el-icon><Star /></el-icon> {{ isFavorite ? '取消收藏' : '收藏商品' }}
    </el-button>
  </div>

  <div class="buy-button-container">
    <el-button
      type="primary"
      class="buy-btn"
      :disabled="product.status !== 1"
      @click="goToOrdersPage">
      <el-icon><ShoppingCart /></el-icon> 立即购买
    </el-button>
  </div>
</div>
        </div>
      </div>

      <!-- 商品详情描述 -->
      <div class="product-description">
        <h2 class="section-title">商品详情</h2>
        <div class="description-content">
          {{ product.description || '暂无描述' }}
        </div>
      </div>

      <!-- 推荐商品 -->
      <div v-if="recommendedProducts.length > 0 && showRecommendations" class="recommended-products">
        <h2 class="section-title">相关推荐</h2>
        <div class="product-list">
          <div class="product-item" v-for="item in recommendedProducts" :key="item.id" @click="goToProduct(item.product_code || item.id)">
            <img :src="getProductImage(item)" class="product-thumbnail" />
            <div class="product-item-info">
              <div class="product-item-name">{{ item.name }}</div>
              <div class="product-item-price">¥{{ item.price }}</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import apiClient from '@/utils/request'
import { ElMessage } from 'element-plus'
import { ArrowLeft, Star } from '@element-plus/icons-vue'
import axios from 'axios'
import {DEFAULT_AVATAR} from '@/utils/userUtils'
const showRecommendations = ref(false)
const route = useRoute()
const router = useRouter()
const product = ref({})
const isFavorite = ref(false)
const recommendedProducts = ref([])
const loading = ref(true)
const error = ref(false)
const handleAvatarError = () => {
  if (product.value.seller) {  // 修改判断条件
    product.value.seller.avatar = DEFAULT_AVATAR
  }
}
// 立即购买
const buyNow = () => {
  if (!product.value.product_code) {
    ElMessage.warning('商品信息不完整')
    return
  }
  if (product.value.status !== 1) {
    ElMessage.warning('商品已售出，无法购买')
    return
  }
  // 跳转到订单页面，传递商品编码作为参数
  router.push(`/orders?product_code=${product.value.product_code}`)
}
// 获取商品详情
const fetchProductDetail = async () => {
  loading.value = true
  error.value = false
  try {
    // 使用product_code而不是id
    const productCode = route.params.product_code

    if (!productCode) {
      error.value = true
      ElMessage.error('商品编码不存在')
      loading.value = false
      return
    }
    
    // 确保URL格式正确，移除可能的重复斜杠
    const apiUrl = `/api/products/buyer/${productCode}/`.replace(/\/+/g, '/')
    await new Promise(resolve => setTimeout(resolve, 200)) // 延迟300ms加载
    const response = await axios.get(apiUrl)    
    if (response.data) {
      product.value = response.data
      await fetchRecommendedProducts()
      showRecommendations.value = true
    } else {
      error.value = true
      ElMessage.error('获取商品详情失败: 返回数据为空')
    }
  } catch (err) {
    console.error('获取商品详情失败:', err)
    console.error('错误详情:', err.response?.data || err.message)
    error.value = true
    
    // 根据错误类型提供更具体的错误信息
    if (err.response) {
      if (err.response.status === 404) {
        ElMessage.error('商品不存在或已被删除')
      } else if (err.response.status === 400) {
        ElMessage.error('请求参数错误: ' + (err.response.data?.detail || '未知错误'))
      } else {
        ElMessage.error(`服务器错误 (${err.response.status}): 请稍后再试`)
      }
    } else if (err.request) {
      ElMessage.error('网络请求失败: 请检查网络连接')
    } else {
      ElMessage.error('获取商品详情失败: ' + err.message)
    }
  } finally {
    loading.value = false
    showRecommendations.value = true
  }
}

// 获取商品图片
const getProductImage = (item) => {
  if (item.images && item.images.length > 0) {
    const image = item.images[0]
    return image.url || image.thumbnail_url || '/no-image.png'
  }
  return '/no-image.png'
}


const getCategoryName = (categoryId) => {
  const categoriesStr = localStorage.getItem('categories')
  if (categoriesStr) {
    try {
      const categoriesData = JSON.parse(categoriesStr)
      
      // 先在父分类中查找
      const parentCategory = categoriesData.data.find(cat => cat.id === categoryId)
      if (parentCategory) {
        return parentCategory.display_name
      }
      
      // 如果父分类中没找到，则在所有子分类中查找
      for (const parent of categoriesData.data) {
        if (parent.children) {
          const childCategory = parent.children.find(child => child.id === categoryId)
          if (childCategory) {
            return childCategory.display_name
          }
        }
      }
    } catch (error) {
      console.error('解析分类数据失败:', error)
    }
  }
  return `未知分类(${categoryId})`
}

// 检查是否已收藏
const checkIfFavorite = async () => {
  try {
    const productCode = product.value.product_code
    if (!productCode) return
    
    const response = await apiClient.get(`/api/products/buyer/${productCode}/check-favorites`)
    isFavorite.value = response.data.isFavorite
  } catch (error) {
    console.error('检查收藏状态失败:', error)
  }
}

// 获取推荐商品
const fetchRecommendedProducts = async () => {
  try {
    const categoryId = product.value.category;
    if (!categoryId) {
      console.log('无商品分类信息');
      recommendedProducts.value = [];
      return;
    }

    const productCode = product.value.product_code;
    const response = await axios.get(
      `/api/products/categories/${categoryId}/products/?exclude=${productCode}`
    );

    // 正确处理分页结构
    recommendedProducts.value = Array.isArray(response.data.results)
      ? response.data.results
      : [];

    console.log('推荐商品数据:', recommendedProducts.value);
  } catch (error) {
    console.error('获取推荐商品失败:', error);
    recommendedProducts.value = [];
  }
}



// 转换配送方式为文本
const getDeliveryMethodText = (method) => {
  const methods = {
    1: '自提',
    2: '校内配送',
    3: '快递'
  }
  return methods[method] || '未知'
}

// 修改后的 toggleFavorite 函数
const toggleFavorite = async () => {
  try {
    const productCode = product.value.product_code
    if (!productCode) {
      ElMessage.warning('商品信息不完整')
      return
    }
    
    if (isFavorite.value) {
      await apiClient.delete(`/api/products/buyer/${productCode}/favorites/`)
      ElMessage.success('已取消收藏')
    } else {
      // POST 请求时，第二个参数是请求体，第三个参数是配置对象
      await apiClient.post(`/api/products/buyer/${productCode}/favorites/`)
      ElMessage.success('收藏成功')
    }
    isFavorite.value = !isFavorite.value
  } catch (error) {
    console.error('操作失败:', error)
    if (error.response?.status === 401) {
      ElMessage.error('请先登录')
    } else {
      ElMessage.error(error.response?.data?.error || '操作失败，请稍后再试')
    }
  }
}

// 联系卖家
const contactSeller = async () => {
  if (!product.value.seller) {
    ElMessage.warning('无法获取卖家信息')
    return
  }

  try {
    const response = await axios.get(`/api/products/buyer/${route.params.product_code}`)
    product.value = {
      ...response.data,
      product_code: response.data.product_code // ✅ 确保返回数据包含product_code
    }
  } catch (error) {
    console.error('获取商品失败:', error)
    ElMessage.error('商品不存在或已下架')
    router.push('/')
  }
}

const goToOrdersPage = () => {
  router.push({
    path: '/orders',
    query: {
      product:product.value.id, // ✅ 传递正确的参数名称
      product_code: route.params.product_code // ✅ 传递正确的参数名称
    }
  })
}

// 跳转到其他商品详情
const goToProduct = (productCode) => {
  if (!productCode) {
    ElMessage.warning('商品信息不完整')
    return
  }
  router.push(`/product/${productCode}`)
}

onMounted(() => {

  fetchProductDetail()
  setTimeout(() => {
    showRecommendations.value = true
  }, 500)
// 可以临时添加调试代码
console.log('showRecommendations:', showRecommendations.value)
console.log('recommendedProducts:', recommendedProducts.value)

})
</script>

<style scoped>
.product-detail-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
}

.back-button {
  cursor: pointer;
  display: inline-flex;
  align-items: center;
  color: #409eff;
  font-size: 14px;
}

.loading-container, .error-container {
  padding: 40px 20px;
  text-align: center;
  background-color: #f5f7fa;
  border-radius: 8px;
  margin-bottom: 20px;
}

.product-main {
  display: flex;
  flex-wrap: wrap;
  gap: 30px;
  margin-bottom: 30px;
  max-width: 1200px;
  margin: 0 auto;
}

.product-images {
  flex: 1;
  min-width: 500px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.carousel-image {
  width: 100%;
  height: 100%;
  object-fit: contain;
  background-color: #f5f7fa;
}

.no-image {
  height: 400px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f7fa;
  color: #909399;
  font-size: 16px;
}

.product-info {
  flex: 1.5; /* 增加商品信息区域的比例 */
  min-width: 400px; /* 增加最小宽度 */
  padding: 20px; /* 增加内边距 */
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.product-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 12px;
}

.product-name {
  font-size: 24px;
  margin: 0;
  font-weight: 600;
  color: #303133;
  flex: 1;
}

.seller-meta {
  display: flex;
  align-items: center;
  gap: 8px;
  background: #f2f6fc;
  padding: 6px 12px;
  border-radius: 20px;
  margin-left: auto;
}

.seller-avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
}

.seller-name {
  color: #606266;
  font-size: 14px;
}

.product-price {
  font-size: 28px;
  color: #ff6b6b;
  font-weight: bold;
  margin: 20px 0;
}

.product-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
}

.product-status, .product-category {
  color: #606266;
  font-size: 14px;
}

.status-active {
  color: #67c23a;
  font-weight: 500;
}

.status-inactive {
  color: #f56c6c;
  font-weight: 500;
}

.info-section {
  margin-top: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 15px;
  color: #303133;
}

.delivery-method, .delivery-location {
  margin-top: 10px;
  color: #606266;
  font-size: 14px;
}

.action-buttons-container {
  margin-top: 30px;
}

.action-buttons {
  display: flex;
  gap: 15px;
  margin-bottom: 15px; /* 增加与购买按钮的间距 */
}

.contact-btn {
  flex: 1;
  height: 40px;
  font-size: 14px;
  background-color: #45a049;
  border-color: #45a049;
}

.contact-btn:hover, .contact-btn:focus {
  background-color: #3c8a3f;
  border-color: #3c8a3f;
}

.favorite-btn {
  flex: 1;
  height: 40px;
  font-size: 14px;
  color: #606266;
  border-color: #dcdfe6;
}

.favorite-btn.is-favorite {
  color: #ff6b6b;
  border-color: #ff6b6b;
}

.buy-button-container {
  display: flex;
  justify-content: center;
}

.buy-btn {
  min-width: 200px;
  width: 100%; /* 让按钮宽度与上方两个按钮总宽度一致 */
}

.product-description {
  margin-top: 30px;
  padding: 25px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.description-content {
  margin-top: 15px;
  white-space: pre-wrap;
  color: #606266;
  line-height: 1.6;
  font-size: 14px;
}

.recommended-products {
  margin-top: 40px;
}

.product-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 20px;
  margin-top: 20px;
}

.product-item {
  cursor: pointer;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transition: transform 0.3s;
  background-color: #fff;
}

.product-item:hover {
  transform: translateY(-5px);
}

.product-thumbnail {
  width: 100%;
  height: 150px;
  object-fit: cover;
}

.product-item-info {
  padding: 10px;
}

.product-item-name {
  font-size: 14px;
  margin-bottom: 5px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  color: #303133;
}

.product-item-price {
  color: #ff6b6b;
  font-weight: bold;
  font-size: 14px;
}

@media (max-width: 768px) {
  .product-main {
    flex-direction: column;
  }
  .product-images {
    max-width: 100%; /* 在移动端取消最大宽度限制 */
  }
  .product-info {
    min-width: 100%; /* 在移动端占满整个宽度 */
    padding: 20px; /* 移动端减小内边距 */
  }
  .product-header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .seller-meta {
    margin-left: 0;
    width: 100%;
  }
  
  .product-list {
    grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  }
  
  .action-buttons {
    flex-direction: column;
  }
}
</style>